<template>
  <div class="platform h-full">
    <div class="platform-nav flex">
      <div
        @click="curIndex = index"
        :class="curIndex === index ? 'active' : ''"
        v-for="(item, index) in navList"
        :key="index"
      >
        {{ item.name }}
      </div>
    </div>
    <div class="platform-content">
      <div class="item-title">配置信息</div>
      <a-form :model="form" ref="formRef" v-bind="formItemLayout">
        <a-form-item name="name" label="平台名称" required>
          <a-input
            maxLength="15"
            placeholder="请输入"
            v-model:value.trim="form.name"
          ></a-input>
        </a-form-item>
        <a-form-item name="logo" label="上传文件" required>
          <a-upload-dragger
            name="logo"
            accept=".png,.svg"
            maxCount="1"
            v-model:fileList="form.logo"
            :before-upload="beforeUpload"
            :customRequest="handleUpload"
            list-type="picture"
            @remove="handleRemove"
          >
            <br />
            <p class="ant-upload-drag-icon flex justify-center">
              <img src="../../assets/images/upload-icon.png" />
            </p>
            <p class="ant-upload-text">请上传企业LOGO</p>
            <p class="ant-upload-hint">
              （图片大小5M以内，图片支持svg、png格式）
            </p>
            <br />
          </a-upload-dragger>
        </a-form-item>
        <a-form-item label=" " class="button-item">
          <a-button
            key="submit"
            type="submit"
            :loading="submitLoading"
            @click="handleFinish"
          >
            提交
          </a-button>
          <a-button
            key="submit"
            type="cancel"
            @click="resetConfig"
            :loading="resetLoading"
          >
            重置
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { platformStore } from '@/store'
import { getSysInfo, upload, save, reset } from '@/api/platform'
const formItemLayout = {
  labelCol: { style: 'width: 80px' }
}

const curIndex = ref(0)
const navList = [
  {
    name: '平台配置'
  }
]
const store = platformStore()
const formRef = ref()
const form = reactive({
  name: '',
  logo: [],
  path: ''
})
form.name = store.name

const submitLoading = ref(false)
// 提交按钮
const handleFinish = async () => {
  await formRef.value.validateFields()
  submitLoading.value = true
  save({
    name: form.name,
    filePath: form.path
  })
    .then(() => {
      getPlatform()
      submitLoading.value = false
      message.success('提交成功,刷新页面后生效')
    })
    .catch(() => {
      submitLoading.value = false
    })
}

const getPlatform = () => {
  getSysInfo().then((res) => {
    if (res) {
      form.name = res.name
      form.path = res.filePath
      store.setPlatform(res)
    }
  })
}

const resetLoading = ref(false)
// 重置按钮
const resetConfig = async () => {
  formRef.value.resetFields()
  resetLoading.value = true
  reset()
    .then(() => {
      getPlatform()
      resetLoading.value = false
      message.success('重置成功,刷新页面后生效')
    })
    .catch(() => {
      resetLoading.value = false
    })
}

// 校验失败返回reject
const returnReject = () => {
  return new Promise((resolve, reject) => {
    reject(new Error('上传图片校验不通过'))
  })
}
// 上传前校验
const beforeUpload = async (file: any) => {
  if (form.logo.length === 1) {
    form.logo.splice(0, 1)
  }
  return new Promise((resolve, reject) => {
    // 图片大小不超过5M，图片高度固定为30px，宽度最宽为350px，图片格式svg，png
    const accept = ['image/png', 'image/svg+xml']
    if (file.size > 5 * 1024 * 1024) {
      message.error('图片大小不符合要求，不能超过5M')
      return returnReject()
    } else if (!accept.includes(file.type)) {
      message.error('图片格式不符合要求，仅支持svg、png格式')
      return returnReject()
    } else {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = (e: any) => {
        const img = new Image()
        img.src = e.target.result
        img.onload = () => {
          if (img.height !== 30 || img.width > 350) {
            message.error('图片尺寸不符合要求，高度必须30，宽度不可超过350')
            return returnReject()
          } else {
            resolve(file)
          }
        }
      }
    }
  })
}

// 自定义上传
const handleUpload = async (data: any) => {
  const file = data.file
  if (!file) return
  const formData = new FormData()
  formData.append('file', file)
  upload(formData)
    .then((res) => {
      form.path = res
    })
    .catch(() => {
      if (form.logo.length === 1) {
        form.logo.splice(0, 1)
        form.path = ''
      }
    })
}

// 删除图片
const handleRemove = () => {
  if (form.logo.length === 1) {
    form.logo.splice(0, 1)
  }
  form.path = ''
}
onMounted(() => {})
</script>
<style lang="less" scoped>
/* stylelint-disable-next-line string-quotes */
.platform {
  overflow-x: hidden;
  overflow-y: auto;
  height: 100%;

  &-nav {
    height: 2.25rem;
    line-height: 2.25rem;
    border-bottom: 1px solid #f0f0f0;

    > div {
      height: 2.25rem;
      font-size: 1rem;
      color: #707479;
      line-height: 1.25rem;
      font-weight: 400;
      cursor: pointer;
    }

    > div + div {
      margin-left: 1.875rem;
    }

    .active {
      color: @primary-color;
      font-weight: bold;
      border-bottom: 2px solid @primary-color;
    }
  }

  &-content {
    padding-top: 1.25rem;
    height: calc(100% - 2.25rem);

    .ant-input-affix-wrapper {
      width: 37.5rem !important;
    }
  }
}
</style>
<style lang="less">
.platform {
  .ant-upload.ant-upload-drag {
    width: 37.5rem !important;
    border: none;

    .ant-upload-drag-icon {
      margin-bottom: 1rem;

      img {
        width: 2.25rem;
        height: 2.25rem;
      }
    }

    .ant-upload-text {
      font-size: 0.875rem;
      font-weight: bold;
      color: #000;
    }

    .ant-upload-hint {
      font-weight: 400;
      color: #707479;
    }
  }

  .ant-upload-list {
    width: 37.5rem !important;

    .ant-upload-list-item {
      border: none;
    }

    .ant-upload-list-item-thumbnail,
    .ant-progress-line {
      display: none;
    }
  }

  .button-item {
    .ant-form-item-label > label::after {
      content: '';
    }

    .ant-btn-submit {
      margin-right: 1.25rem;
    }
  }
}
</style>
